<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\jia;

use app\api\model\jia\Works as WorksModel;
use app\common\model\jia\House as HouseModel;
use app\common\model\jia\WorksLog as WorksLogModel;
use app\store\service\wxapp\Message as MessageService;
use think\facade\Db;

/**
 * 模型
 * Class Shop
 * @package app\store\model\store
 */
class House extends HouseModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'is_delete',
        'store_id',
        'create_time',
        'update_time',
    ];
    public function getList($params)
    {
        // 参数验证和分页计算
        $page     = max(1, intval($params['page'] ?? 1));
        $pageSize = max(1, intval($params['pageSize'] ?? 20));
        $start    = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [['is_delete', '=', 0]];

        if (! empty($params['value'])) {
            $where[] = ['code|name', 'like', "%{$params['value']}%"];
        }

        if (! empty($params['deviceId'])) {
            $where[] = ['code', '=', $params['deviceId']];
        }

        // 获取房间列表
        $lists = $this
            ->where($where)
            ->field('house_id as roomId, name as roomName')
            ->order(['create_time' => 'desc'])
            ->limit($start, $pageSize)
            ->select()
            ->toArray();

        if (empty($lists)) {
            return [];
        }

        // 批量获取所有房间的床位信息（解决N+1查询）
        $roomIds = array_column($lists, 'roomId');

        $allBeds = Db::name('order')->alias('o')
            ->where('o.house_id', 'in', $roomIds)
            ->where('o.service_status', '>', 0)
            ->where('o.order_status', 10)
            ->where('o.paidan_time', '>', 0)
            ->where('o.is_settled', 0)
            ->field('o.house_id, o.bed_no as redId, o.real_name as name, o.order_no as id, o.sex as gender')
            ->order('o.house_id, o.bed_no')
            ->group('o.order_id')
            ->select()
            ->toArray();

        // 按房间ID分组床位信息
        $bedsGrouped = [];
        foreach ($allBeds as $bed) {
            $roomId = $bed['house_id'];
            unset($bed['house_id']); // 移除不需要的字段

            if (! isset($bedsGrouped[$roomId])) {
                $bedsGrouped[$roomId] = [];
            }
            $bedsGrouped[$roomId][] = $bed;
        }

        // 将床位信息关联到对应的房间
        foreach ($lists as &$list) {
            $list['beds'] = $bedsGrouped[$list['roomId']] ?? [];
        }

        return $lists;
    }

    public function getBedList($params)
    {
        // 参数验证
        if (empty($params['roomid'])) {
            return [];
        }

        $roomId = (int) $params['roomid'];

        // 1. 获取订单列表
        $lists = Db::name('order')->alias('o')
            ->where('o.house_id', $roomId)
            ->where('o.service_status', '>', 0)
            ->where('o.order_status', 10)
            ->where('o.is_settled', 0)
            ->where('o.is_delete', 0)
            ->field('o.bed_no as redId, o.real_name as name, o.order_no as id, o.sex as gender')
            ->select()
            ->toArray();

        if (empty($lists)) {
            return [];
        }

        // 2. 获取工作项目列表
        $works = Db::name('jia_works')
            ->field('works_id as workId, name as workName')
            ->order('sort asc')
            ->select()
            ->toArray();

        if (empty($works)) {
            // 如果没有工作项目，为每个订单设置空数组
            foreach ($lists as &$list) {
                $list['works'] = [];
            }
            return $lists;
        }

        // 3. 批量获取所有工作日志（解决N+1查询问题）
        $orderNos = array_column($lists, 'id');
        $workIds  = array_column($works, 'workId');

        // 一次性查询所有相关的工作日志
        $allWorkLogs = Db::name('jia_works_log')
            ->where('order_no', 'in', $orderNos)
            ->where('works_id', 'in', $workIds)
            ->field('works_id, order_no, create_time')
            ->order('create_time DESC')
            ->select()
            ->toArray();

        // 4. 按订单号和工作ID分组工作日志
        $groupedLogs = [];
        foreach ($allWorkLogs as $log) {
            $key = $log['order_no'] . '_' . $log['works_id'];
            if (! isset($groupedLogs[$key])) {
                $groupedLogs[$key] = [];
            }
            $groupedLogs[$key][] = $log['create_time'];
        }

        // 5. 构建工作项目模板（包含careTimes）
        $worksTemplate = [];
        foreach ($works as $work) {
            $worksTemplate[$work['workId']] = [
                'workId'    => $work['workId'],
                'workName'  => $work['workName'],
                'careTimes' => [], // 默认空数组
            ];
        }

        // 6. 组装最终结果
        foreach ($lists as &$list) {
            $listWorks = [];

            foreach ($worksTemplate as $workId => $workItem) {
                $key = $list['id'] . '_' . $workId;
                if (isset($groupedLogs[$key])) {
                    $workItem['careTimes'] = $groupedLogs[$key];
                }
                $listWorks[] = $workItem;
            }

            $list['works'] = $listWorks;
        }

        return $lists;
    }

    public function getWorkList($params)
    {
        // 1. 使用更清晰的变量名
        $orderNo = $params['id'];
        $today   = date('Y-m-d');

        // 2. 合并前三个查询，减少数据库交互
        $houseInfo = Db::name('order')
            ->alias('o')
            ->join('jia_room_house jrh', 'o.house_id = jrh.house_id')
            ->join('jia_works_template jwt', 'jrh.template_id = jwt.template_id')
            ->where('o.order_no', $orderNo)
            ->field('jwt.works_ids')
            ->find();

        if (empty($houseInfo)) {
            return [];
        }

        // 3. 安全地处理JSON解码

        $worksIdsData = json_decode($houseInfo['works_ids'], true);
        $worksIds     = array_column($worksIdsData, 'value');

        if (empty($worksIds)) {
            return [];
        }

        // 4. 获取工作列表
        $worksModel = new WorksModel();
        $works      = $worksModel->getShowList($worksIds);

        if (empty($works)) {
            return [];
        }

        // 5. 批量查询工作日志，避免N+1查询
        $workIds   = array_column($works, 'workId');
        $worksLogs = (new WorksLogModel())
            ->where('date', $today)
            ->where('order_no', $orderNo)
            ->where('works_id', 'in', $workIds)
            ->order('create_time DESC')
            ->select()
            ->toArray();

        // 6. 按works_id分组日志记录
        $logsGrouped = [];
        foreach ($worksLogs as $log) {
            $logsGrouped[$log['works_id']][] = $log;
        }

        // 7. 关联数据到对应工作
        foreach ($works as &$work) {
            $workId            = $work['workId'];
            $work['careTimes'] = $logsGrouped[$workId] ?? [];
        }

        return $works;
    }

    public function getWorkhistory($params)
    {

        // 获取列表数据
        $where = [];
        if (isset($params['dateRange']) && ! empty($params['dateRange'])) {
            if ($params['dateRange'] == 1) {
                //今日
                $time    = strtotime(Date('Y-m-d'));
                $where[] = ['w.create_time', '>', $time];
            }
            if ($params['dateRange'] == 2) {
                //近3日
                $time    = strtotime(Date('Y-m-d')) - 86400 * 3;
                $where[] = ['w.create_time', '>', $time];
            }
            if ($params['dateRange'] == 3) {
                //近7日
                $time    = strtotime(Date('Y-m-d')) - 86400 * 7;
                $where[] = ['w.create_time', '>', $time];
            }
            if ($params['dateRange'] == 4) {
                //近30日
                $time    = strtotime(Date('Y-m-d')) - 86400 * 30;
                $where[] = ['w.create_time', '>', $time];
            }
        }
        $where[]  = ['w.works_id', '=', $params['workid']];
        $start    = ($params['page'] - 1) * $params['pageSize'];
        $end      = $params['page'] * $params['pageSize'];
        $model    = new WorksLogModel;
        $timeList = $model->alias('w')
            ->join('order', 'order.order_no=w.order_no')
            ->where($where)->where('w.order_no', $params['id'])
            ->where('order.order_status', 10)
            ->where('order.is_delete', 0)
            ->field('w.log_id,w.create_time,w.order_no as id,w.remark,w.work_name as workName,w.unit,w.value')
            ->limit($start, $end)
            ->order('w.log_id desc')
            ->select()
            ->toArray();

        return $timeList;
    }
    public function workUpdate($params)
    {

        //操作记录
        if (isset($params['time'])) {
            $date = Date('Y-m-d', (int) $params['time']);
        } else {
            $date = Date('Y-m-d');
        }
        $orderNo = isset($params['orderNo']) ? $params['orderNo'] : $params['id'];

        $log = Db::name('jia_works_log')
            ->where('date', $date)
            ->where('order_no', $orderNo)
            ->where('works_id', $params['workid'])
            ->find();

        //查询是否限制次数
        $type = Db::name('jia_works')->where('works_id', $params['workid'])->value('type');

        $order = Db::name('order')->where('order_no', $orderNo)->field('extract_clerk_id,real_name')->find();

        if ($log && $type == 1) {
            throwError('该服务今天已完成');

        } else {

            if ($order['extract_clerk_id'] == 0) {
                throwError('请先派单给陪护员');
            }

            $works = Db::name('jia_works')->where('works_id', $params['workid'])->field('name,remark,time')->find();

            $data['works_id']  = $params['workid'];
            $data['work_name'] = $works['name'];
            $data['time']      = $works['time'];
            $data['remark']    = $works['remark'];
            $data['order_no']  = $orderNo;
            if ($params['model'] == 0) {
                $data['value'] = '';
                $data['unit']  = '';
            } else {
                $data['value'] = isset($params['tag']) ? $params['tag'] : '';
                $data['unit']  = isset($params['unit']) ? $params['unit'] : '';
            }

            $data['store_id']    = self::$storeId;
            $data['create_time'] = time();
            $data['date']        = $date;
            $data['is_send']     = 0;

            $data['real_name'] = $order['real_name'] ? $order['real_name'] : '';
            Db::name('jia_works_log')->insert($data);

            //更新
            $one = Db::name('jia_works_log')->where('order_no', $orderNo)
                ->where('works_id', $params['workid'])
                ->where('date', $date)->order('create_time desc')->find();

            $totalNum = Db::name('jia_works_log')->where('order_no', $orderNo)
                ->where('works_id', $params['workid'])
                ->where('date', $date)->count();
            $totalValue = 0;
            if ($params['model'] == 1) {
                //计量项目
                $totalValue = Db::name('jia_works_log')->where('order_no', $orderNo)
                    ->where('works_id', $params['workid'])
                    ->where('date', $date)->sum('value');
            }

            Db::name('jia_works_log')->where('log_id', $one['log_id'])
                ->update(['total_num' => $totalNum, 'total_value' => $totalValue]);

            //发送公众号信息
            //$this->sendMessage($data);
        }

        return true;
    }

    public function syncData($list)
    {
        if (empty($list['records'])) {
            return true;
        }

        // 1. 批量获取works_id
        $workIds = array_column($list['records'], 'workid');
        $workIds = array_unique(array_filter($workIds));

        if (empty($workIds)) {
            return true;
        }

        // 2. 一次性查询所有works数据
        $worksMap = Db::name('jia_works')
            ->where('works_id', 'in', $workIds)
            ->field('works_id, name, remark, time')
            ->select()
            ->column(null, 'works_id');

        // 3. 批量插入数据
        $insertData  = [];
        $currentTime = time();

        foreach ($list['records'] as $params) {
            $worksId = (int) ($params['workid'] ?? 0);

            if (! $worksId || ! isset($worksMap[$worksId])) {
                continue; // 跳过无效数据
            }

            $works        = $worksMap[$worksId];
            $insertData[] = [
                'works_id'    => $worksId,
                'work_name'   => $works['name'] ?? '',
                'time'        => $works['time'] ?? 0,
                'remark'      => $works['remark'] ?? '',
                'order_no'    => $params['id'] ?? 0,
                'store_id'    => self::$storeId,
                'create_time' => $params['time'] ?? $currentTime,
            ];

            // 分批插入，避免单次数据量过大
            if (count($insertData) >= 1000) {
                Db::name('jia_works_log')->insertAll($insertData);
                $insertData = [];
            }
        }

        // 插入剩余数据
        if (! empty($insertData)) {
            Db::name('jia_works_log')->insertAll($insertData);
        }

        return true;
    }

    private function sendMessage()
    {
        $data = Db::name('jia_works_log')->where('is_send', 0)->find();

        $order = Db::name('order')->where('order_no', $data['order_no'])
            ->field('extract_clerk_id,order_id,user_id,mobile,real_name')->find();

        $goodsName = Db::name('order_goods')->where('order_id', $order['order_id'])->value('goods_name');
        $clerkName = Db::name('store_shop_clerk')->where('clerk_id', $order['extract_clerk_id'])->value('real_name');

        $unionid  = Db::name('user_oauth')->where('user_id', $order['user_id'])->value('unionid');
        $opend_id = Db::name('user_oauth_wxapp')->where('unionid', $unionid)->value('open_id');
        $list[]   = [$opend_id];

        $users = Db::name('user_mobile_bind')
            ->where('mobile', $order['mobile'])->select()->toArray();
        $userIds = array_column($users, 'user_id');

        //其他绑定的用户
        $users = Db::name('user_oauth')
            ->where('oauth_type', 'WXOFFICIAL')->where('user_id', 'in', $userIds)
            ->field('oauth_id')->select()->toArray();
        $users = array_column($users, 'oauth_id');

        $lists = array_merge([$opend_id], $users);
        $lists = array_unique($lists);

        foreach ($lists as $key => $opend_id) {
            if ($opend_id) {
                // 执行发送
                $MessageService         = new MessageService;
                $content['template_id'] = 'npMp42HWu2YNBvMw2gVxEcOcFt4GNDlcA8pK8IGSVCo';
                //$content['page']        = 'pagesNew/order/runner/detail?orderId=' . $order['order_id'];
                $content['page'] = '';
                if ($data['value'] != '') {
                    $content['data']['thing2'] = $data['work_name'] . '(' . $data['value'] . $data['unit'] . ')';
                } else {
                    $content['data']['thing2'] = $data['work_name'];
                }

                $content['data']['time3']   = Date('Y年m月d日 H:i', (int) $data['create_time']);
                $content['data']['thing13'] = $clerkName;
                $content['data']['thing11'] = $order['real_name'];

                $content['data']['short_thing6'] = '已完成';

                //暂时注释
                $MessageService->send($opend_id, $content);
            }
        }

        return true;

    }
}
